package com.qf.base.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 雪花算法的工具类
 * @author xuzhong
 */
@Component
public class SnowFlakeUtil {

    /**
     * 机房id
     */
    @Value("${snowFlake.dataCenterId:0}")
    private long dataCenterId;

    /**
     * 机器id
     */
    @Value("${snowFlake.worker:0}")
    private long workerId;


    private long timeStartPoint=1659078804920L;


    private long sequence;



    private long lastTime=-1;

    private long nextTime(long lastTimestamp){
        long timestamp=System.currentTimeMillis();
        while(timestamp<=lastTimestamp){
            timestamp=System.currentTimeMillis();
        }
        return timestamp;
    }
    public static final int MAX_SEQUENCE=4096;
    public synchronized long nextId(){
        //0|000 0000 0000 0000 0000 0000 0000 0000
        //0000 0000 00|00 000|0 0000| 0000 0000 0000

        //获取当前时间
        long timestamp=System.currentTimeMillis();
        if(timestamp<lastTime){
            return -1;
        }
        if(timestamp==lastTime){
            //0~4095
            sequence++;
            if(sequence==MAX_SEQUENCE){
                timestamp=nextTime(lastTime);
                sequence=0;
            }
        }else{
            sequence=0;
        }

        long id=(0<<63)|
                ((timestamp-timeStartPoint)<<22)|
                        (dataCenterId<<17)|
                        (workerId<<12)|
                        (sequence);
        lastTime=timestamp;
        return id;
    }





    public static void main(String[] args) {
        SnowFlakeUtil snowFlakeUtil=new SnowFlakeUtil();
        for (;;){
            System.out.println(snowFlakeUtil.nextId());
        }

    }
}
